'use strict';

const UserValidationRule = {
  username: {
    type: 'username'
  },
  email: {
    type: 'email'
  },
  nick: {
    type: 'string',
    required: false
  },
  mobile: {
    type: 'number',
    required: false
  },
  user_type: {
    type: 'enum',
    values: ['student', 'teacher']
  }
}

module.exports = app => {
  class UserController extends app.Controller {
    async index (ctx) {
      let res = await ctx.app.model.user.doc.find().select('id user_name')

      ctx.body = res.map(x => x.toObject())
    }

    async create (ctx) {
      let [error] = ctx.app.validator.validate(UserValidationRule, ctx.request.body) || []

      if (ctx.helper.abortOnError({
        ctx,
        code: 1,
        error: error,
      })) return

      let user = new ctx.app.model.user.doc(ctx.request.body)
      let res = await user.save().catch(ctx.helper.genAppError({ctx}))

      if (ctx.helper.abortOnError({
        ctx,
        error: res,
        code: res.code,
        message: res.code === 11000 ? 'duplicate user_name' : 'fail to create user'
      })) return

      ctx.helper.rest.resp({ctx, data: user.toObject({virtuals: true})})
    }

    async bulk_create () {

    }

    async update (ctx) {
      ctx.body = 'update'
    }

    async edit (ctx) {
      ctx.body = 'edit'
    }

    async destroy (ctx) {
      ctx.body = 'destroy'
    }
  }

  return UserController;
};
